import os
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

def save_images_from_url(url, folder):
    # 发送HTTP GET请求获取网页内容
    response = requests.get(url)
    response.raise_for_status()  # 确保请求成功

    # 使用BeautifulSoup解析HTML内容
    soup = BeautifulSoup(response.text, 'html.parser')

    # 创建保存图片的文件夹如果它不存在
    if not os.path.exists(folder):
        os.makedirs(folder)

    # 查找所有的<img>标签并提取src属性
    for img_tag in soup.find_all('img'):
        # 获取图片的URL
        img_url = img_tag.get('src')
        if not img_url:
            continue

        # 处理相对URL
        img_url = urljoin(url, img_url)

        # 获取图片的文件名
        filename = os.path.basename(img_url)

        # 下载图片并保存到本地文件夹
        try:
            img_data = requests.get(img_url).content
            with open(os.path.join(folder, filename), 'wb') as file:
                file.write(img_data)
            print(f"图片已保存：{filename}")
        except requests.RequestException as e:
            print(f"无法下载图片：{img_url}，错误：{e}")

# 网页的URL
url = 'http://www.people.com.cn'

# 本地保存图片的文件夹
folder = 'downloaded_images'

# 调用函数保存图片
save_images_from_url(url, folder)